import request from "@/utils/request";
import service from "./request";
import store from "@/store";
/**
 * 通用js方法封装处理
 */

const baseURL = service.baseURL;

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === "string") {
      time = time.replace(new RegExp(/-/gm), "/");
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  var search = params;
  search.params = {};
  if (null != dateRange && "" != dateRange) {
    if (typeof propName === "undefined") {
      search.params["beginTime"] = dateRange[0];
      search.params["endTime"] = dateRange[1];
    } else {
      search.params[propName + "BeginTime"] = dateRange[0];
      search.params[propName + "EndTime"] = dateRange[1];
    }
  }
  return search;
}

// 回显数据字典
export function selectDictLabel(datas = [], value) {
  var actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].codevalue == "" + value) {
      actions.push(datas[key].codename);
      return true;
    }
  });
  return actions.join("");
}

//回显数据字典
export function selectDictName(datas, value) {
  var actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].codevalue == "" + value) {
      actions.push(datas[key].codename);
      return true;
    }
  });
  return actions.join("") || value;
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
  var actions = [];
  var currentSeparator = undefined === separator ? "," : separator;
  var temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    Object.keys(datas).some((key) => {
      if (datas[key].dictValue == "" + temp[val]) {
        actions.push(datas[key].dictLabel + currentSeparator);
      }
    });
  });
  return actions.join("").substring(0, actions.join("").length - 1);
}

// 通用下载方法
export function download(fileName) {
  window.location.href =
    baseURL +
    "/common/download?fileName=" +
    encodeURI(fileName) +
    "&delete=" +
    true;
}

// 字符串格式化(%s )
export function sprintf(str) {
  var args = arguments,
    flag = true,
    i = 1;
  str = str.replace(/%s/g, function() {
    var arg = args[i++];
    if (typeof arg === "undefined") {
      flag = false;
      return "";
    }
    return arg;
  });
  return flag ? str : "";
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

// undefined,null转化为指定值
export function transformEmtyValue(str, transfer = "") {
  if (str == undefined || str == null) {
    return transfer;
  }
  return str;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
export function handleTree(data, id, parentId, children, rootId) {
  id = id || "id";
  parentId = parentId || "parentId";
  children = children || "children";
  if (rootId != null) {
    rootId =
      rootId ||
      Math.min.apply(
        Math,
        data.map((item) => {
          return item[parentId];
        })
      ) ||
      0;
  }
  //对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data));
  //循环所有项
  const treeData = cloneData.filter((father) => {
    let branchArr = cloneData.filter((child) => {
      //返回每一项的子级数组
      return father[id] == child[parentId];
    });
    branchArr.length > 0 ? (father.children = branchArr) : "";
    //返回第一层
    return father[parentId] == rootId;
  });
  return treeData != "" ? treeData : data;
}

/**
 * 深度复制数据
 * @param {*} params
 * @returns
 */
export function deepCopyData(params) {
  if (typeof params !== "object" || params === null) {
    // 为null||undefined
    let copy = params;
    return copy;
  }
  let copyArr = params.constructor === Array ? [] : {}; // 判断是数组还是对象
  for (let i in params) {
    if (typeof params[i] === "object") {
      // 判断是引用类型还是其他类型
      copyArr[i] = deepCopyData(params[i]); // 引用类型的话进行递归操作
    } else {
      copyArr[i] = params[i]; // 其他类型直接赋值
    }
  }
  return copyArr;
}

/**
 * 把数据字典转换成map格式
 * @param {*} dictdata
 */
export function dictToMap(dictdata = []) {
  if (!dictdata) {
    return {};
  }

  let obj = {};
  dictdata.forEach((ele) => {
    obj[ele.codevalue] = ele.codename;
  });
  return obj;
}

/**
 * 合并数据
 * @param {*} params
 * @returns
 */
export function mergeData(orgParams, params) {
  const paramType = Object.prototype.toString.call(params);
  if (paramType != "[object Object]" && paramType != "[object Array]") {
    orgParams = params;
    return;
  }
  for (const key in params) {
    if (Object.hasOwnProperty.call(params, key)) {
      const element = params[key];
      if (element == null || element == undefined) {
        continue;
      }
      const type = Object.prototype.toString.call(element);
      if (type == "[object Object]" || type == "[object Array]") {
        mergeData(orgParams[key], element);
      } else {
        orgParams[key] = element;
      }
    }
  }
}

// 获取第一个工厂-车间-产线
export function getOwnFirstLine(permitList = null) {
  permitList = permitList || store.getters.permitList || [];

  // result[0]为工厂对象，result[1]为车间对象，result[2]为产线对象
  let result = [null, null, null];

  if (permitList?.length) {
    const factory = permitList[0];
    result[0] = factory;
    if (factory.workshopVos?.length) {
      const workshop = factory.workshopVos[0];
      result[1] = workshop;
      if (workshop.productionLineVos?.length) {
        const line = workshop.productionLineVos[0];
        result[2] = line;
      }
    }
  }

  return result;
}

//过滤最后一级children为空数组数据
export function getTreeData(data) {
  for (var i = 0; i < data.length; i++) {
    if (data[i]?.children?.length) {
      // children若不为空数组，则继续 递归调用 本方法
      data[i].isLast = false;
      getTreeData(data[i].children);
    } else {
      // children若为空数组，则将children设为undefined
      data[i].children = undefined;
      data[i].isLast = true; //判断是否最后一级
    }
  }
  return data;
};

//树状结构转数组
export function treeToArr(tree) {
  // 判断 tree 是否有值，无返回 []
  if (!Array.isArray(tree) || !tree.length) return []
  let res = []
  tree.forEach(v => {
    // tree的每个元素都 放入到 res里面
    res.push(v)
    if (v.children) {
      // 有children 就把 children数据递归 返回  依次放到 res里面
      res.push(...treeToArr(v.children))
    }
  })
  return res
}

export function toFix(num = 0, fix = 0) {
  num = Number(num) || 0
  let _fix = Math.pow(10, fix);
  return Math.round(num * _fix) / _fix;
}

//按照班次计算时间间隔
export function toTeamTimeSep(num = 1) {
  let nowTimeStamp = new Date().getTime(); //当前时间
  let nowTime = this.parseTime(new Date()); //当前时间格式化
  let eightAm = nowTime.slice(0, 11) + "08:00:00"; //当前早上8点
  let eightAmStamp = new Date(eightAm).getTime(); //以当前时间早上八点为基础
  let todayStart = null;
  let todayEnd = null;
  let sepDayStart = null;
  if (nowTimeStamp > eightAmStamp) { //当前时间如果小于08:00:00
    todayStart = eightAmStamp; //今日08:00
    todayEnd = eightAmStamp + 24 * 60 * 60 * 1000 * 1 - 1000; //明日07:59
  } else {
    todayStart = eightAmStamp - 24 * 60 * 60 * 1000 * 1; //昨天08:00
    todayEnd = eightAmStamp - 1000; //今日07:59分
  }
  sepDayStart = todayEnd - 24 * 60 * 60 * 1000 * Number(num) + 1000; //间隔日期(到07:59)
  if (num == 1) {
    return [this.parseTime(todayStart), this.parseTime(todayEnd)]
  } else {
    return [this.parseTime(sepDayStart), this.parseTime(todayEnd)]
  }
}